// Modules to control application life and create native browser window
const {app, BrowserWindow, Menu,ipcMain,globalShortcut} = require('electron')
const remote = require('@electron/remote/main')
const Store = require('electron-store')
// 渲染进程使用需要初始化
Store.initRenderer()
// remote 初始化
remote.initialize()
const path = require('path')

console.log(process.platform)
let mainId = null;

function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        x: 100,
        y: 100,
        show: false,
        width: 800,
        height: 600,
        maxHeight: 900,
        maxWidth: 1200,
        minHeight: 300,
        minWidth: 400,
        icon: '闪电.ico',
        // frame:false, // 全屏
        // transparent: true,// 透明度
        // autoHideMenuBar: true,
        // backgroundColor: "#56000000",
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true, // 允许渲染进程使用 node 环境
            contextIsolation: false,
            enableRemoteModule: true
        }
    })

    // 自定义需要的菜单项
    let menuTemp = [
        {
            label: '文件',
            submenu: [
                {
                    label: '打开文件夹', click: () => {
                        console.log("执行打开文件夹操作")
                    }
                },
                {
                    type: 'separator'
                },
                {label: '导入'},
                {label: '关于', role: 'about'},
            ]
        },
        {
            label: '角色', submenu: [
                {
                    label: '复制', role: 'copy'
                },

                {
                    label: '剪切', role: 'cut'
                },

                {
                    label: '粘贴', role: 'paste'
                },
                {
                    label: '最小化', role: 'minimize'
                },
            ]
        },
        {
            label: '类型', submenu: [
                {
                    label: '选项1', type: 'checkbox'
                },

                {
                    label: '选项2', type: 'checkbox'
                },

                {
                    label: '选项3', type: 'checkbox'
                },
                {
                    type: 'separator'
                },
                {
                    label: 'item1', type: 'radio'
                },
                {
                    label: 'item2', type: 'radio',click:()=>{
                        BrowserWindow.getFocusedWindow().webContents.send('mtp','来自主进程菜单的消息')
                    }
                },
            ]
        },
        {label: 'windows', type: 'submenu', role: 'windowMenu'},
        {label: 'other',icon:'./open.png',accelerator:'ctrl + o',click:()=>{
            console.log('open操作执行了')
            }},
        {label: '编辑'},
    ]

    // let menu = Menu.buildFromTemplate(menuTemp);
    // Menu.setApplicationMenu(menu)


    // and load the index.html of the app.
    mainWindow.loadFile('index.html')

    mainWindow.on("ready-to-show", () => {
        mainWindow.show()

        // 允许iframe访问第三方url
        // mainWindow.webContents.session.webRequest.onHeadersReceived({ urls: [ "*://*/*" ] },
        //     (d, c)=>{
        //         if(d.responseHeaders['X-Frame-Options']){
        //             delete d.responseHeaders['X-Frame-Options'];
        //         } else if(d.responseHeaders['x-frame-options']) {
        //             delete d.responseHeaders['x-frame-options'];
        //         }
        //
        //         c({cancel: false, responseHeaders: d.responseHeaders});
        //     }
        // );

    })
    mainId = mainWindow.id

    remote.enable(mainWindow.webContents)

    // 注册快捷键
    let register = globalShortcut.register('ctrl + q',(ev)=>{
        console.log(ev)
        console.log('ctrl + q 快捷键注册成功')
    });
    if(!register){
        console.log('ctrl + q 快捷键注册失败')
    }
    let b = globalShortcut.isRegistered('ctrl + q');
    console.log(b)
    // Open the DevTools.
    // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    createWindow()

    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})

app.on('will-quit',()=>{
    globalShortcut.unregister('ctrl + q')
    // globalShortcut.unregisterAll()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

// 主进程接收消息操作
ipcMain.on('msg',(ev,data)=>{
    console.log(data)
    ev.sender.send('msg1','这是一条来自主进程的异步消息')
})

ipcMain.on('msgSync',(ev,data)=>{
    console.log(data)
    ev.returnValue = '来自主进程的同步消息'
})

ipcMain.on('renderCommunicate',(ev,data)=>{
    console.log(data)
    console.log('主窗口id'+mainId)
    // Create the browser window.
    let newWindow = new BrowserWindow({
        show: false,
        width: 800,
        height: 600,
        icon: '闪电.ico',
        parent: BrowserWindow.fromId(mainId),
        modal:true,
        webPreferences: {
            nodeIntegration: true, // 允许渲染进程使用 node 环境
            contextIsolation: false,
            enableRemoteModule: true
        }
    })

    newWindow.loadFile('newWindow.html')

    newWindow.on("ready-to-show", () => {
        newWindow.show()
    })

    newWindow.on('close',()=>{
        newWindow = null
    })
    newWindow.webContents.openDevTools()

    newWindow.webContents.on('did-finish-load',()=>{
        newWindow.webContents.send('toNewWindow',data)
    })

})
